package com.ztomorrow.ying_cun_plus.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.ztomorrow.ying_cun_plus.dao.mapper.BookChapterMapper;

import com.ztomorrow.ying_cun_plus.dao.po.BookChapter;
import com.ztomorrow.ying_cun_plus.dto.resp.BookChapterRespDto;
import com.ztomorrow.ying_cun_plus.utils.CacheUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import static com.ztomorrow.ying_cun_plus.constant.front.CacheConstant.*;

@Component
@RequiredArgsConstructor
public class BookChapterCacheManager {
    private final CacheUtils cacheUtils;

    private final BookChapterMapper bookChapterMapper;

    /**
     * 根据章节ID获取，章节信息
     */
    public BookChapterRespDto getChapter(Long chapterId) {
        BookChapterRespDto cache = cacheUtils.getCacheOne(
                v -> BeanUtil.copyProperties(v, BookChapterRespDto.class),
                CAFFEINE_BOOK_CHAPTER + chapterId, REDIS_BOOK_CHAPTER + chapterId,
                v -> JSONUtil.toBean(v, BookChapterRespDto.class));
        if (cache != null) return cache;
        BookChapter bookChapter = bookChapterMapper.selectById(chapterId);
        BookChapterRespDto bookChapterRespDto =
                BeanUtil.copyProperties(bookChapter, BookChapterRespDto.class);
        bookChapterRespDto.setChapterWordCount(bookChapter.getWordCount());
        bookChapterRespDto.setChapterUpdateTime(bookChapter.getUpdateTime());
        cacheUtils.saveCacheOne(bookChapterRespDto,
                CAFFEINE_BOOK_CHAPTER + chapterId,
                REDIS_BOOK_CHAPTER + chapterId, REDIS_BOOK_CHAPTER_TTL,
                JSONUtil::toJsonStr);
        return bookChapterRespDto;
    }

}
